// pages/openScreen/openScreen.js
import api from '../../config/api'
import { shareOptions, getUserPermissions } from '../../utils/access'
import request from '../../utils/request'
import {
  getBarAndTitleHeight,
  getXsScreen,
  jump,
  getStorage,
  setStorage,
  goBack,
} from '../../utils/utils'
const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 显示抽大奖按钮
    showBtn:true,
    // 信号栏是否有背景
    hasBg: false,
    // 信号栏高度
    ...getBarAndTitleHeight(),
    // 是否是小屏幕尺寸
    ...getXsScreen(),
    // 进入该页面来源  1-点击分享进入
    fromShare: '',
    // 用户信息
    userData: {},
    // 签到日历数据
    signData: [],
    // 今天签到数据
    todayData: {},
    // 选中的签到奖励数据
    rewardData: {},
    // 签到动态数据
    signDynamicData: [],
    // 当前红包数据
    envelopeData: null,
    // 拆样式
    dismantleClass: '',
    // 金币样式
    goldClass: '',
    // 开红包接口失败
    requestFail: false,
    // 联系我们-整体二维码
    serviceQrcode:
      'https://image-classify.daieco.com/kejian-quanzi/mrm4Z9LEuSF514052d3cebf4e5fff095132b1eb81863.png',
    // 单独二维码
    qrcode:
      'https://image-classify.daieco.com/kejian-quanzi/Iwh5x26q9vzA8a6cd3e1aacd48a9a17f14cd314cd7fb.png',
    // 奖品列表
    couponList: [],
    couponInfo: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      ...getBarAndTitleHeight(),
    })
    if (options?.inviteData) {
      console.log('分享人数据：', options.inviteData)
    }
    if (Number(options?.share) === 2) {
      setStorage('fromShare', 'shareFromWechat')
      setStorage('shareSource', 1)
      setStorage('shareUserId', options?.shareUserId)
      setStorage('activityId', options?.activityId)
    }
    if (Number(options?.share) === 1) {
      setStorage('fromShare', '25DayTask')
      setStorage('inviteData', options?.inviteData)
    }

    this.getSwitch()
  },

  // 获取抽奖展示开关
  getSwitch: async function(){
    const res = await request.get('getSwitchData',{
      switchType:2
    })
    if(res.httpStatus===200){
      this.setData({
        showBtn:res.data[0].miniAppSwitch===1
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.modal = this.selectComponent('#modal')
    this.envelopeModal = this.selectComponent('#envelopeModal')
    this.serviceModal = this.selectComponent('#serviceModal')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let accessType = getStorage('fromShare')
    let isLogin = app.isLogin()
    if (accessType === '25DayTask' || accessType === 'shareFromWechat') {
      this.setData({
        fromShare: accessType,
      })
      // 分享领鸡蛋入口进来的
      if (accessType === 'shareFromWechat' && isLogin) {
        this.saveShareRecord()
      }
    }
    // 获取用户信息
    this.getUserData()
    // 获取签到动态数据
    this.getSignDynamicData()
    this.timeInterval = setInterval(() => {
      this.getSignDynamicData()
    }, 10000)
  },
  // 记录分享关系
  async saveShareRecord() {
    const res = await request.get(`${api.saveShareRecord}`, {
      shareUserId: getStorage('shareUserId'),
    })
    if (res.httpStatus === 200) {
    }
  },
  /**
   * 获取用户信息
   */
  async getUserData() {
    let res = await request.get(api.getUserData, {}, { loading: false })
    if (res.httpStatus === 200) {
      const userData = res.data || {}
      const userInfo = getStorage('userInfo')
      // 设置短昵称
      const nameArray = Array.from(userInfo?.nickName || '')
      const shortName = nameArray.slice(0, 4).join('')
      userData.shortName = nameArray.length > 4 ? `${shortName}...` : shortName
      userData.avatarUrl = userInfo?.avatarUrl

      console.log('用户信息：', userData)
      this.setData({
        userData,
      })
      // 获取签到日历数据
      this.getSignData()
    }
  },
  /**
   * 获取签到日历数据
   */
  async getSignData() {
    let res = await request.get(api.getSignCalendar, {}, { loading: false })
    console.log('签到日历数据:', res)
    if (res.httpStatus === 200) {
      let todayData =
        res.data.find((item) => {
          return item.completing === 1
        }) || {}
      this.setData({
        signData: res.data || [],
        todayData,
      })
    }
  },
  /**
   * 获取签到动态数据
   */
  async getSignDynamicData() {
    let res = await request.get(api.getUserSignDynamic, {}, { loading: false })
    if (res.httpStatus === 200) {
      let signDynamicData = []
      res.data.forEach((item, index) => {
        if (index < 4) {
          signDynamicData.push(item)
        }
      })
      this.setData({
        signDynamicData,
      })
    }
  },
  // 日历点击操作
  async signHandle(e) {
    // 登录、目标小区可点击
    if (this.data.userData.hasLogin) {
      if (this.loading) return
      this.loading = true
      let { item } = e.currentTarget.dataset
      if (item.hasCompletedSign && !item.hasCoupon) {
        //已完成、无奖励
        this.loading = false
        return
      } else if (item.hasCompletedSign && item.hasCoupon) {
        //已完成、有奖励
        await this.getRewardData(item.signTimes, item)
        this.loading = false
        return
      } else if (!item.hasCompletedSign && item.completing === 1) {
        //今天、未完成，直接去签到拍照
        jump('categoryPhoto', { source: 1, signDays: item.signTimes - 1 })
        this.loading = false
        return
      } else if (
        !item.hasCompletedSign &&
        !item.hasCoupon &&
        item.completing === 2
      ) {
        //未来的、未完成、无奖励
        this.loading = false
        return
      } else if (
        !item.hasCompletedSign &&
        item.hasCoupon &&
        item.completing === 2
      ) {
        //未来的、未完成、有奖励
        //抽奖按钮 单独控制
        if(item.couponName==='抽奖机会'&&!this.data.showBtn){
          this.loading = false
          return
        }else{
          await this.getRewardData(item.signTimes, item)
          this.loading = false
          return
        }
      }
      this.loading = false
    }
  },
  /**
   * 获取奖励数据
   * @param {String} 签到时间
   */
  async getRewardData(time, item) {
    this.setData({
      rewardData: {},
    })
    let res = await request.get(
      api.getUserSignReward,
      { signNum: time },
      { loading: false }
    )
    if (res.httpStatus === 200) {
      this.setData({
        rewardData: res.data || {},
        couponList: item.couponNames,
        couponInfo: item,
      })
      this.modal.show()
    }
  },

  // 用户信息卡操作
  async userHandle(e) {
    if (this.loading) return
    this.loading = true
    let type = e.currentTarget.dataset.type
    if (type === 'login') {
      //去登陆
      setStorage('redirectPath', '/pages/openScreen/openScreen')
      app.login()
      this.loading = false
    } else if (type === 'sign') {
      //去签到拍照
      jump('categoryPhoto', {
        source: 1,
        signDays: this.data.userData.signTimes,
      })
      this.loading = false
    } else if (type === 'certification') {
      //去认证居住地
      jump('residenceCertification')
      this.loading = false
    }
    this.loading = false
  },

  // 奖励弹窗操作-去签到
  modalConfirm() {
    jump('categoryPhoto', {
      source: 1,
      signDays: this.data.todayData.signTimes - 1,
    })
    this.modal.hide()
  },
  // 关闭奖励弹窗
  modalClose() {
    this.modal.hide()
  },

  // 跳转抽奖页面
  async jumpLottery() {
    if (this.data.userData?.hasLogin) {
      jump('lottery')
    } else {
      setStorage('redirectPath', '/pages/openScreen/openScreen')
      const userInfo = await app.login()
    }
  },
  // 返回
  back() {
    goBack()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // 清除定时器
    clearInterval(this.timeInterval)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    const isLogin = app.isLogin()
    let fromShare = getStorage('fromShare')
    if (isLogin && fromShare) {
      removeStorage('fromShare')
    }
    // 清除定时器
    clearInterval(this.timeInterval)
  },
  // 打开红包弹窗
  openModal(event) {
    this.setData({
      requestFail: false,
      envelopeData: event?.currentTarget?.dataset?.item || {},
      dismantleClass: 'scale',
    })
    this.envelopeModal.show()
  },
  // 关闭红包弹窗
  closeModal() {
    if (!this.data?.envelopeData?.signInRedPacket) {
      this.envelopeModal.hide()
    }
  },
  // 打开红包
  openEnvelope() {
    if (this.loading) return
    this.loading = true
    // 隐藏拆
    this.setData(
      {
        dismantleClass: 'hide',
      },
      () => {
        setTimeout(async () => {
          const { envelopeData, signData } = this.data
          // 显示金币并旋转
          this.setData({
            goldClass: 'spin',
            dismantleClass: '',
          })
          // 接口开始时间
          const startTime = Date.now()
          // 调接口开红包
          const res = await request.get(
            api.collarEnvelope,
            { signInId: envelopeData.signInId },
            { loading: false }
          )
          console.log('开红包接口返回：', res)
          // 接口响应时间
          const requestTime = Date.now() - startTime
          // 不足2000毫秒延迟
          if (requestTime < 2000) {
            await new Promise((resolve) => {
              setTimeout(() => {
                resolve()
              }, 2000 - requestTime)
            })
          }
          if (res?.httpStatus === 200) {
            // 隐藏金币
            this.setData(
              {
                goldClass: 'hide',
              },
              () => {
                // 显示金额
                setTimeout(() => {
                  envelopeData.signInRedPacket = false
                  envelopeData.amount = res?.data || 0
                  const newSignData = signData.map((item) => {
                    if (item.signTimes === envelopeData.signTimes) {
                      item.signInRedPacket = false
                      item.amount = res?.data || 0
                    }
                    return item
                  })
                  this.setData({
                    goldClass: '',
                    envelopeData,
                    signData: newSignData,
                  })
                  this.loading = false
                }, 540)
              }
            )
          } else {
            // 隐藏金币显示拆
            this.setData({
              dismantleClass: 'scale',
              goldClass: '',
              requestFail: true,
            })
            this.loading = false
          }
        }, 540)
      }
    )
  },
  // 点击“联系我们”
  handleContact() {
    this.serviceModal.show()
  },
  // 保存图片
  handleSavePhoto() {
    // if(this.loading) return
    // this.loading = true
    wx.getImageInfo({
      src: this.data.serviceQrcode,
      success: function (sres) {
        // 调用系统方法，下载图片并保存
        getUserPermissions(
          'writePhotosAlbum',
          (res) => {
            if (res) {
              wx.showToast({
                title: '保存成功',
                icon: 'success',
              })
            } else {
              wx.showToast({
                title: '保存失败',
                icon: 'error',
              })
            }
          },
          { filePath: sres.path }
        )
      },
    })
    // // 10s后才能再次保存
    // setTimeout(()=>{
    //   this.loading = false
    // },10000)
  },
  // 关闭“专属客服”弹窗
  serviceModalClose() {
    this.serviceModal.hide()
  },
  /**
   * 查看图片
   */
  handlePreview() {
    const { qrcode } = this.data
    wx.previewImage({
      current: qrcode,
      urls: [qrcode],
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},
  // 页面滚动事件
  onPageScroll(e) {
    this.setData({
      hasBg: e?.scrollTop > 20,
    })
  },
  // 拨打电话
  call() {
    wx.makePhoneCall({
      phoneNumber: '0371-53376036'
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    return shareOptions('award', e)
  },
})
